import {User} from '@/entitys/base/user.entity';
import {Injectable} from '@nestjs/common';
import {Repository} from "typeorm";
import {BaseService} from "@/modules/_/base/base.service";
import {InjectRepository} from '@nestjs/typeorm';
import {ResultUtils} from "@/utils/resultUtils";
import {CacheTokenService} from "@/modules/cache/service/cacheTokenService";
import {RequestService} from "@/modules/request/service/requestService";
import {AuthService} from "@/modules/jwtModule/service/auth.service";
import {ResultType} from "@/typing/request";
import {StatusCode} from "@/typing/statusCode";
import {CompanyService} from "@/modules/company/service/company.service";
import {typeUtils} from "@/utils/typeUtils";
import {classTransformerUtils} from '@/utils/classTransformerUtils';
import { userInfoVo } from '../vo/userInfo.vo';

@Injectable()
export class UserService extends BaseService {

    constructor(
        @InjectRepository(User) private readonly Repository: Repository<User>,
        private readonly CacheTokenService: CacheTokenService,
        private readonly RequestService: RequestService,
        private AuthService: AuthService,
        private CompanyService: CompanyService,
    ) {
        super(Repository);
    }


    async login(userInfo: User): Promise<ResultType<{user: User, token: string}>> {
        try {
            let tokenId = "";
            const user = await this.repository.findOne({where: {phone: userInfo.phone, password: userInfo.password}});
            if (user) {
                const {access_token} = await this.AuthService.createToken(user);

                const setCacheUserResult = await this.CacheTokenService.setCacheToken(access_token);

                if (setCacheUserResult.err) {
                    return ResultUtils.unknownError();
                }

                tokenId = setCacheUserResult.data;

                return ResultUtils.success({
                    user,
                    token: tokenId,
                    opCode: StatusCode.T1
                });
            }
            return ResultUtils.success({
                opCode: StatusCode.T100
            });
        } catch (e) {
            return ResultUtils.unknownError();
        }
    }

    async getMyUserInfo() {
        const user = this.RequestService.getUser();

        const {companyId} = user;

        const userInfoVO = classTransformerUtils.plainToClassExcludeExtraneousValues(userInfoVo, user, {excludeExtraneousValues: true});

        if (!typeUtils.isUndefined(companyId)) {
            const getCompanyResult = await this.CompanyService.queryById(companyId);

            if (getCompanyResult.err) {
                return ResultUtils.unknownError();
            }

            const companyInfo = getCompanyResult.data;

            if (!typeUtils.isUndefined(companyInfo)) {
                userInfoVO.setCompany(companyInfo);
            }
        }

        return ResultUtils.success(userInfoVO);
    }
}
